package com.cyj.springbootredis.config;

import com.cyj.springbootredis.Listener.RedisMessageListener;
import com.cyj.springbootredis.messageHand.MessageSubscriber;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @description: 指定 RedisTemplate 序列化
 * @Author C_Y_J
 * @create 2021/9/29 10:40
 **/
@Configuration
public class RedisTemplateConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // 使用String序列化redis的key值（默认使用JDK的序列化方式）
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());

        // 方法一
        // 使用GenericJackson2序列化redis的value值（默认使用JDK的序列化方式）
//        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        //  方法二
        //  使用GenericJackson2序列化redis的value值（默认使用JDK的序列化方式）
//        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = getJackson2JsonRedisSerializer();
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 参考：https://www.cnblogs.com/puzhiwei/p/12519304.html
     *
     * @return
     */
    private Jackson2JsonRedisSerializer<Object> getJackson2JsonRedisSerializer() {

        ObjectMapper objectMapper = new ObjectMapper()
                // 指定要序列化的域,field,get和set,以及修饰符范围,
                // ANY是都有包括private和public
                .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
                .enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
        return stringRedisTemplate;
    }

    /**
     * 消息监听器，使用MessageAdapter可实现自动化解码及方法代理
     *
     * @param messageSubscriber
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(MessageSubscriber messageSubscriber) {
        MessageListenerAdapter adapter = new MessageListenerAdapter(messageSubscriber, "onMessage");
        // 一定要指定序列化方式，默认为StringSerialization,会导致在对象和map等等不可用
        adapter.setSerializer(new JdkSerializationRedisSerializer());
        return adapter;
    }

    /**
     * redis消息监听器容器
     * 可以添加多个监听不同话题的redis消息监听器，只需要把消息监听器和相应的消息订阅处理器绑定，
     * 该消息监听器通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     *
     * @param connectionFactory
     * @param listenerAdapter
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter, RedisMessageListener redisMessageListener) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 订阅了一个通道
        container.addMessageListener(listenerAdapter, new PatternTopic("RedisTopic_1"));
        // 这个container可以添加多个messageListener
        container.addMessageListener(redisMessageListener, new PatternTopic("RedisTopic_2"));

        return container;
    }

}